﻿#if UNITY_EDITOR
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace UFrame
{
    /// <summary>
    /// 设置自动化UI
    /// </summary>
    public class SetAutoUIWindow : BaseTestWindow
    {
        public string uiName = string.Empty;

        public static int autoInputId = 0;
        public static int autoInputGroupId = 0;
        public static string ui = "AutoInputUI";
        public static string strAutoInput = "AutoInput";
        public static string strAutoInputGroup = "AutoInputGroup";

        public GameObject CreateNode()
        {
            GameObject go = GetAutoUIRoot();
            RectTransform rt = null;
            GameObject autoInput = new GameObject();
            autoInput.transform.SetParent(go.transform);
            rt = autoInput.AddComponent<RectTransform>();
            rt.anchoredPosition = Vector2.zero;
            rt.localScale = Vector3.one;
            Image image = autoInput.AddComponent<Image>();
            image.color = new Color32(136, 236, 236, 255);

            return autoInput;
        }

        private void OnGUI()
        {
            uiName = EditorGUILayout.TextField("UIName", uiName);

            if (GUILayout.Button("创建AutoInput"))
            {
                GameObject autoInput = CreateNode();
                var input = autoInput.AddComponent<AutoTestInput>();
                autoInput.name = strAutoInput + autoInputId;
                input.id = autoInputId;
                autoInputId++;
            }

            if (GUILayout.Button("创建AutoInputGroup"))
            {
                GameObject autoInput = CreateNode();
                var input = autoInput.AddComponent<AutoTestGroup>();
                autoInput.name = strAutoInputGroup + autoInputGroupId;
                input.id = autoInputGroupId;
                autoInputGroupId++;
            }

            if (GUILayout.Button("保存序列化信息"))
            {
                GameObject uiRoot = Selection.activeGameObject;
                if (uiRoot == null || uiRoot.GetComponent<RectTransform>() == null)
                {
                    Debug.LogError("没有选中UI无法保存相关信息,请选中UI根节点");
                    return;
                }

                AutoTestInput[] t = uiRoot.GetComponents<AutoTestInput>();
                AutoTestGroup[] g = uiRoot.GetComponents<AutoTestGroup>();

                //序列化
                UITestGroupJson uiGroup = new UITestGroupJson();

                uiGroup.UIName = uiRoot.name;
                foreach (var item in t)
                {
                    AutoTestInputJson i = new AutoTestInputJson();
                    i.id = item.id;
                    RectTransform rt = item.transform as RectTransform;
                    i.position = rt.anchoredPosition;
                    uiGroup.inputList.Add(i);
                }

                foreach (var item in g)
                {
                    AutoTestGroupJson i = new AutoTestGroupJson();

                    RectTransform rt = item.transform as RectTransform;
                    i.position = rt.anchoredPosition;

                    int[] ids = new int[item.randomTestList.Count];
                    for (int j = 0; j < item.randomTestList.Count; j++)
                    {
                        ids[j] = item.randomTestList[j].id;
                    }

                    i.ids = ids;


                    int index = 0;
                    foreach (var order in item.orderToTest)
                    {
                        string[] arg = order.Split(',');
                        int[] orderAry = new int[arg.Length];
                        i.orderToTestList.Add(new OrderToTestJson()
                        {
                            weight = index,
                            ids = orderAry,
                        });

                        index++;
                    }


                    uiGroup.groupList.Add(i);
                }

                string json = JsonUtility.ToJson(uiGroup);
                SaveJson(uiGroup.UIName, json);
            }


            if (GUILayout.Button("召唤测试UI"))
            {
                string newPath = string.Format(DefineAutoTest.path, uiName);
                string uiPath = Application.dataPath + newPath;

                if (!File.Exists(uiPath))
                {
                    Debug.LogError("测试文件不存在");
                    return;
                }

                string json = File.ReadAllText(newPath, Encoding.Unicode);
                UITestGroupJson uiGroup = JsonUtility.FromJson<UITestGroupJson>(json);

                //销毁原来的
                GameObject go = GameObject.Find(ui);
                DestroyImmediate(go);

                CallTestUI(uiGroup);
            }
        }

        public void SaveJson(string name, string json)
        {
            string newPath = string.Format(DefineAutoTest.path, name);
            string uiPath = Application.dataPath + newPath;
            File.WriteAllText(uiPath, json, Encoding.Unicode);
        }

        public GameObject GetAutoUIRoot()
        {
            GameObject go = GameObject.Find(ui);
            if (go == null)
            {
                go = new GameObject(ui);
                go.AddComponent<RectTransform>();
                var canvas = GameObject.FindObjectOfType<Canvas>();
                go.name = ui;


                if (canvas != null)
                {
                    go.transform.SetParent(canvas.transform);
                }
                else
                {
                    Debug.LogError("没有找到Canvas");
                }

                go.transform.localScale = Vector3.one;
            }
            else
            {
            }

            return go;
        }

        public void CallTestUI(UITestGroupJson uiGroup)
        {
            List<AutoTestInput> inputList = new List<AutoTestInput>();
            foreach (var group in uiGroup.inputList)
            {
                GameObject autoInput = CreateNode();
                var input = autoInput.AddComponent<AutoTestInput>();
                autoInput.name = strAutoInput + group.id;
                input.id = group.id;
                inputList.Add(input);
            }

            //创建新的UI测试
            foreach (var group in uiGroup.groupList)
            {
                GameObject autoInput = CreateNode();
                var input = autoInput.AddComponent<AutoTestGroup>();
                autoInput.name = strAutoInputGroup + group.id;
                input.id = group.id;

                input.randomTestList = new List<AutoTestInput>();
                foreach (var id in group.ids)
                {
                    foreach (var item in inputList)
                    {
                        if (id == item.id)
                        {
                            input.randomTestList.Add(item);
                            break;
                        }
                    }
                }

                //顺序测试

                foreach (var order in group.orderToTestList)
                {
                    string orderStr = string.Empty;

                    foreach (var item in order.ids)
                    {
                        orderStr += item + ",";
                    }

                    orderStr = orderStr.TrimEnd(',');
                    input.orderToTest.Add(orderStr);
                }
            }
        }


        [MenuItem("Plateface/UGUI/设置测试UI")]
        static void ShowEditor()
        {
            SetAutoUIWindow editor = EditorWindow.GetWindow<SetAutoUIWindow>();
            editor.Show(true);
        }
    }
}
#endif